<?php


namespace app\home\controller;


use app\base\BaseController;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class Punter
 * @package app\home\controller
 * 客户档案
 */
class Punter extends BaseController
{
    protected $table='purveyor';
    protected $title='客户档案';
    private $sessionKey='pagePunter';
    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
        $param=$this->request->param();
        if (request()->isAjax()) {
            $haveAuth=false;
            $otherAu=true;
            if ($this->isHaveAuth('see_all')){
                $haveAuth=true;
            }elseif($this->isHaveAuth('see_depart')){
                $haveAuth=true;
                $where[]=['departId','in',$this->dSons];
            }elseif($this->isHaveAuth('see_self')){
                $haveAuth=true;
                $where[]=['createId','=',$this->uid];
            }elseif($this->isHaveAuth('seefp')){
                $haveAuth=true;
                $otherAu=false;
            }
            if (!$haveAuth){
                return table_assign(1,'暂无查看权限');
            }
            $where[]=['status','>',-1];
            $where[]=['dw_type','=',2];
            if (isset($this->param['status'])&&$this->param['status']){
                $where[]=['status','=',$this->param['status']];
            }
            if (isset($this->param['name'])&&$this->param['name']){
                $where[]=['name|contact|phoneNum|code','like','%'.$this->param['name'].'%'];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $sql = Db::name($this->table)
                ->where($where)
                ->field('*')
                ->order("id DESC");
                if ($this->isHaveAuth('seefp')&&!$otherAu){

                    $sql->where(function ($query){
                        $query->where('saleIds','=' ,$this->uid);
                        $query->whereOr('saleIds','like',$this->uid.',%');
                        $query->whereOr('saleIds','like','%,'.$this->uid.',%');
                        $query->whereOr('saleIds','like','%,'.$this->uid);
                        return $query;
                    });
                }

                $list=$sql->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        $id = isset($param['id']) ? $param['id'] : 0;
        if (request()->isAjax()) {
            $param=$this->param;
            $conMx=$param['conMx']??[];
            $saveMx=$param['saveMx']??[];

            $param['update_time']=time();
            $code=$param['code']??'';
            $whreCode[]=['deleted','=',0];
            $whreCode[]=['dw_type','=',2];
            $whreCode[]=['code','=',$code];
            if ($param['id'] > 0){
                $whreCode[]=['id','<>',$param['id']];
            }
            $haveCode=Db::name($this->table)->where($whreCode)->count();
            if ($haveCode){
                return to_assign(1,'已存在相同的纳税');
            }
            Db::startTrans();
            try {
                if ($param['id'] > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $param,$this->title);
                } else {
                    $param['createId']=$this->uid;
                    $param['departId']=$this->did;
                    $param['dw_type']=2;
                    $param['create_time'] = time();
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $param,$this->title);
                }

                if ($conMx){
                    $conData=[];
                    $cType=$conMx['type']??[];
                    $cname=$conMx['name']??[];
                    $cjobName=$conMx['jobName']??[];
                    $caddress=$conMx['address']??[];
                    $cphone=$conMx['phone']??[];
                    foreach ($cType as $ck=>$cv){
                        $conData[]=[
                            "type" => $cType[$ck]??'',
                            "name" => $cname[$ck]??'',
                            "jobName" => $cjobName[$ck]??'',
                            "address" => $caddress[$ck]??'',
                            "phone" => $cphone[$ck]??'',
                            'purveyorId'=>$id,
                            'departId'=>$this->did,
                            'createId'=>$this->uid,
                            'create_time'=>time(),
                            'update_time'=>time()

                        ];
                    }
                    Db::name('purveyor_member')->insertAll($conData);
                }
                if ($saveMx){
                    $saveData=[];
                    $sType=$saveMx['type']??[];
                    $sname=$saveMx['name']??[];
                    $sjobName=$saveMx['jobName']??[];
                    $saddress=$saveMx['address']??[];
                    $sphone=$saveMx['phone']??[];
                    $saddType=$saveMx['addType']??[];
                    foreach ($sType as $sk=>$sv){
                        $saveData[]=[
                            "type" => $sType[$sk]??'',
                            "name" => $sname[$sk]??'',
                            "jobName" => $sjobName[$sk]??'',
                            "address" => $saddress[$sk]??'',
                            "phone" => $sphone[$sk]??'',
                            "addType" => $saddType[$sk]??'',
                            'purveyorId'=>$id,
                            'departId'=>$this->did,
                            'createId'=>$this->uid,
                            'create_time'=>time(),
                            'update_time'=>time()

                        ];
                    }
                    Db::name('purveyor_member')->insertAll($saveData);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败：'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $contactList=[];
            $receiverList=[];
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                View::assign('detail', $detail);
                $contactList=Db::name('purveyor_member')
                    ->where('purveyorId',$id)->where('type',1)->where('status',1)
                    ->select();

                $receiverList=Db::name('purveyor_member')
                    ->where('purveyorId',$id)->where('type',2)->where('status',1)
                    ->select();

            }
            $adminList=Db::name('admin')->where('id','>',1)->where('status',1)->field('id,name')->select();
            View::assign('adminList', $adminList);
            view::assign('contactList',$contactList);
            view::assign('receiverList',$receiverList);
            View::assign('id', $id);
            return view('form');
        }
    }

    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
//            if (in_array(218,explode(',',$id))){
//                return to_assign(1, "此数据禁止删除");
//            }
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                Db::name('purveyor_member')->where('purveyorId','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/4/1
     * 启用/禁用
     */
    public function doCheck()
    {
        $param = get_params();
        $updata['update_time']=time();
        $updata['status']=$param['status'];
        $res = Db::name($this->table)->where('id','in',$this->param['id'])->update($updata);
        if ($res) {
            if($param['status'] == 2){
                add_log('disable', $param['id'], $param,$this->title);
            }
            else if($param['status'] == 1){
                add_log('recovery', $param['id'], $param,$this->title);
            }
            return to_assign();
        }
        else{
            return to_assign(0, '操作失败');
        }
    }

    public function importData()
    {
        Db::startTrans();
        try {
            if (!isset($_FILES['file'])){
                throw new Exception('请选择上传文件');
            }
            //限制上传表格类型
            $fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
            //application/vnd.ms-excel  为xls文件类型
            if ($fileExtendName != 'xlsx') {
                throw new Exception('必须为excel表格，且必须为xlsx格式！');
            }

            if (is_uploaded_file($_FILES['file']['tmp_name'])) {
                // 有Xls和Xlsx格式两种
//            $objReader = \IOFactory::createReader('Xlsx');
                $objReader = IOFactory::createReader('Xlsx');

                $filename = $_FILES['file']['tmp_name'];

                $objPHPExcel = $objReader->setReadDataOnly(true)->load($filename);  //$filename可以是上传的表格，或者是指定的表格
                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $importData = [];
                $names=[];
                $codes=[];
                $registAdds=[];
                $phoneNums=[];
                $bankCards=[];
                $banks=[];
//                $bankNames=[];
                $bankNums=[];
                $saleIdss=[];
                $contarcts=[];
                $contarctAdds=[];
                $contarctPhones=[];
                $saveUsers=[];
                $saveAdds=[];
                $savePhones=[];
                $saveAddTypes=[];
                //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
                for ($j = 2; $j <= $highestRow; $j++) {
                    $name=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getFormattedValue();
                    $code=$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getFormattedValue();
                    $registAdd=$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getFormattedValue();
                    $phoneNum=$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getFormattedValue();
                    $bank=$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getFormattedValue();
//                    $bankName=$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                    $bankCard=$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getFormattedValue();
                    $bankNum=$objPHPExcel->getActiveSheet()->getCell("G" . $j)->getFormattedValue();
                    $saleIds=$objPHPExcel->getActiveSheet()->getCell("H" . $j)->getFormattedValue();
                    $contarct=$objPHPExcel->getActiveSheet()->getCell("I" . $j)->getFormattedValue();
                    $contarctAdd=$objPHPExcel->getActiveSheet()->getCell("J" . $j)->getFormattedValue();
                    $contarctPhone=$objPHPExcel->getActiveSheet()->getCell("K" . $j)->getFormattedValue();
                    $saveUser=$objPHPExcel->getActiveSheet()->getCell("L" . $j)->getFormattedValue();
                    $saveAdd=$objPHPExcel->getActiveSheet()->getCell("M" . $j)->getFormattedValue();
                    $savePhone=$objPHPExcel->getActiveSheet()->getCell("N" . $j)->getFormattedValue();
                    $saveAddType=$objPHPExcel->getActiveSheet()->getCell("O" . $j)->getFormattedValue();
                    if ($code){
                        $has=Db::name($this->table)->where('status','>',-1)
                            ->where('code',$code)
                            ->where('dw_type',2)
                            ->count();
                        if ($has){
                            throw new Exception($j-1 .'行纳税号重复');
                        }
                    }
                    if ($name){
                        $names[]=$name;
                        $codes[]= $code;
                        $registAdds[]=$registAdd;
                        $phoneNums[]= $phoneNum;
                        $banks[]= $bank;
//                        $bankNames[]=$bankName;
                        $bankCards[]=$bankCard;
                        $bankNums[]=   $bankNum;
                        $saleIdss[]=$saleIds;
                        $contarcts[]=$contarct;
                        $contarctAdds[]=$contarctAdd;
                        $contarctPhones[]=$contarctPhone;
                        $saveUsers[]=$saveUser;
                        $saveAdds[]=$saveAdd;
                        $savePhones[]=$savePhone;
                        $saveAddTypes[]=$saveAddType;
                    }

                }

                $res=$this->createImportData($names,$codes,$registAdds,
                    $phoneNums,$banks,$bankCards,$bankNums,$saleIdss,$contarcts,$contarctAdds
                    ,$contarctPhones,$saveUsers,$saveAdds,$savePhones,$saveAddTypes);
                if ($res['code']!=1){
                    throw new Exception($res['msg']);
                }
                $data=$res['data'];
                foreach ($data as $v){
                    $inszhu=$v['zhu'];
                    $inszi=$v['zi'];
                    $pId=Db::name($this->table)->insertGetId($inszhu);
                    $ziData=[];
                    foreach ($inszi as $ky=>&$z){
                        $z['purveyorId']=$pId;
                        $z['createId']=$this->uid;
                        $z['departId']=$this->did;
                        $z['create_time']=time();
                        $z['update_time']=time();
                        if ($inszi['name']){
                            $ziData[]=$z;
                        };
                    }
                    Db::name('purveyor_member')->insertAll($ziData);
                }
                if ($data){
                    Db::name($this->table)->insertAll($importData);
                    add_log('import', '', $data,$this->title);
                }
                Db::commit();
            }
        }catch (Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();

    }

    public function createImportData($names,$codes,$registAdds, $phoneNums,$banks,$bankCards,$bankNums,$saleIdss,$contarcts,$contarctAdds,$contarctPhones,$saveUsers,$saveAdds,$savePhones,$saveAddTypes)
    {
        $uniName=array_unique($names);
        $zhudata=[];
        $ziContract=[];
        $ziSave=[];
        foreach ($names as $k=>$v){
            if (!isset($zhudata[$v])){
                $zhudata[$v]=[
                    "name" => $names[$k],
                    "code" => $codes[$k],
                    "registAdd" => $registAdds[$k],
                    "phoneNum" => $phoneNums[$k],
                    "bank" => $banks[$k],
//                    "bankName" => $bankNames[$k],
                    "bankCard" => $bankCards[$k],
                    "bankNum" => $bankNums[$k],
                    "saleIds" => $saleIdss[$k],
                    "deleted" =>0,
                    "dw_type" =>2,
                    "createId" =>$this->uid,
                    "departId" =>$this->did,
                    "create_time"=>time(),
                    'update_time'=>time()
                ];
            }
            $ziContract[$v][]=[
                'name'=>$contarcts[$k],
                'phone'=>$contarctPhones[$k],
                'address'=>$contarctAdds[$k],
                'addType'=>$saveAddTypes[$k],
                'type'=>1
            ];
            $ziSave[$v][]=[
                'name'=>$saveUsers[$k],
                'phone'=>$savePhones[$k],
                'address'=>$saveAdds[$k],
                'addType'=>$saveAddTypes[$k],
                'type'=>2
            ];
        }
        $pData=[];
        foreach ($uniName as $u){
            $zu=$zhudata[$u];
            $cn=$ziContract[$u];
            $sa=$ziSave[$u];
            $zi=array_merge($cn,$sa);
            $pData[]=[
                'zhu'=>$zu,
                'zi'=>$zi
            ];

        }
        return['code'=>1,'msg'=>'','data'=>$pData];
}
    public function exportData()
    {
        $where=session($this->sessionKey);
        $list = Db::name($this->table)
            ->where($where)
            ->field('*')
            ->order("id DESC")->select()->each(function ($item){
                $item['status']=$item['status']==1?'启用':'禁用';
                return $item;
            });
        $title = [
            'id' => 'ID',
            'name' => '客户名称',
            'gz_day' => '挂账日',
            'contact' => '联系人',
            'phoneNum' => '手机号',
            'status' => '状态',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }

    public function info()
    {
        $param=$this->param;
        $id = isset($param['id']) ? $param['id'] : 0;
        $detail = Db::name($this->table)->where('id', $id)->find();
       View::assign('detail', $detail);
        $adminList=Db::name('admin')->where('id','>',1)->where('status',1)->field('id,name')->select();
        View::assign('adminList', $adminList);
        View::assign('id', $id);
        $contactList=Db::name('purveyor_member')
            ->where('purveyorId',$id)->where('type',1)->where('status',1)
            ->select();
        view::assign('contactList',$contactList);
        $receiverList=Db::name('purveyor_member')
            ->where('purveyorId',$id)->where('type',2)->where('status',1)
            ->select();
        view::assign('receiverList',$receiverList);
        return view();
    }

    public function contactAdd()
    {
        $punterId=$this->param['punterId']??'';
        $id=$this->param['id']??0;
        if ($this->request->isAjax()){
            $data=$this->param;
            $data['createId']=$this->uid;
            $data['type']=1;
            $data['departId']=$this->did;
            $data['create_time']=time();
            $data['update_time']=time();
            try {
                if ($id){
                    unset($data['departId']);
                    unset($data['createId']);
//                    unset($data['punterId']);
                    unset($data['create_time']);
                    Db::name('purveyor_member')->where('id',$id)->update($data);
                    add_log('edit', $id, request()->param(),$this->title.' 联系人');
                }else{
                    $id=Db::name('purveyor_member')->insert($data);
                    add_log('add', $id, request()->param(),$this->title.' 联系人');
                }


            }catch (\Exception $e){
                return to_assign(1,'操作失败:'.$e->getMessage());
            }
            return to_assign();
        }else{
            $info=[];
            if ($id){
                $info=Db::name('purveyor_member')->where('id',$id)->find();
            }
            view::assign('detail',$info);
            view::assign('punterId',$punterId);
            view::assign('type',1);
            return view('contactForm');
        }
    }

    public function removeContact()
    {
        $id=$this->param['id'];
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        try {
            Db::name('purveyor_member')->where('type',1)->where('id',$id)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $id, request()->param(),$this->title.' 联系人');
        }catch (\Exception $e){
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();
    }
    public function receiverAdd()
    {
        $punterId=$this->param['punterId']??'';
        $id=$this->param['id']??0;
        if ($this->request->isAjax()){
            $data=$this->param;
            $data['createId']=$this->uid;
            $data['type']=2;
            $data['departId']=$this->did;
            $data['create_time']=time();
            $data['update_time']=time();
            try {
                if ($id){
                    unset($data['departId']);
//                    unset($data['punterId']);
                    unset($data['createId']);
                    unset($data['create_time']);
                    Db::name('purveyor_member')->where('id',$id)->update($data);
                    add_log('edit', $id, request()->param(),$this->title.' 联系人');
                }else{
                    $id=Db::name('purveyor_member')->insert($data);
                    add_log('add', $id, request()->param(),$this->title.' 联系人');
                }
            }catch (\Exception $e){
                return to_assign(1,'操作失败:'.$e->getMessage());
            }
            return to_assign();
        }else{
            $info=[];
            if ($id){
                $info=Db::name('purveyor_member')->where('id',$id)->find();
            }
            view::assign('detail',$info);
            view::assign('punterId',$punterId);
            view::assign('type',2);
            return view('contactForm');
        }
    }

    public function removeReceiver()
    {
        $id=$this->param['id'];
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        try {
            Db::name('purveyor_member')->where('type',2)->where('id',$id)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $id, request()->param(),$this->title.' 联系人');
        }catch (\Exception $e){
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign();
    }
}